using System.Collections;
using UnityEngine;

public class Boomerang : MonoBehaviour
{
    #region 可配置参数

    [Header("运动参数")] [Tooltip("初始速度（建议值12-15）")]
    public float launchSpeed = 12f;

    [Tooltip("水平加速度（负值减速）")] public float acceleration = -3f;
    [Tooltip("最大返回速度绝对值")] public float maxReturnSpeed = 15f;

    [Header("碰撞配置")] [Tooltip("扩展检测范围（应大于碰撞体）")]
    public Vector2 detectionSize = new Vector2(1.2f, 1.8f);

    [Tooltip("地面层级（应包含Ground层）")] public LayerMask groundLayer; // 在Inspector中设置为Layer 6:Ground

    [Header("平台状态")] [Tooltip("平台持续时间")] public float platformDuration = 2f;

    [Header("视觉效果")] [Tooltip("闪烁间隔时间")] public float flashInterval = 0.1f;
    [Tooltip("下坠重力倍数")] public float fallGravity = 3f;
    
    
    private float flyingTimer; // 新增飞行状态计时器
    #endregion

    #region 内部状态

    private Rigidbody2D rb;
    private Collider2D col;
    private SpriteRenderer spriteRenderer;
    private Vector2 moveDirection;

    #endregion

    #region 初始化
    //修改
    AudioSource audioSource;
    
    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
        rb = GetComponent<Rigidbody2D>();
        col = GetComponent<Collider2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        rb.constraints = RigidbodyConstraints2D.FreezeRotation;
    }

    public void Initialize(Vector2 direction)
    {
        flyingTimer = 0f; // 重置计时器
        audioSource.Play();
        moveDirection = direction.normalized;
        // 根据初始方向设置加速度方向（始终与抛出方向相反）
        acceleration = Mathf.Abs(acceleration) * -Mathf.Sign(moveDirection.x);
        EnterFlyingState();
    }

    #endregion

    #region 状态管理
    bool isThrow = false;
    bool isPlatform = false;
    private void FixedUpdate()
    {
        //switch (rb.bodyType)
        //{
        //    case RigidbodyType2D.Dynamic:
                
        //        flyingTimer += Time.fixedDeltaTime; // 累计飞行时间
                
        //        if (flyingTimer >= 10f) // 超过10秒立即销毁
        //        {
        //            Destroy(gameObject);
        //            return;
        //        }
        //        HandleFlyingMovement();
        //        CheckCollisions();
        //        break;

        //    case RigidbodyType2D.Kinematic:
        //        if ((platformDuration -= Time.fixedDeltaTime) <= 0)
        //            EnterFallingState();
        //        break;
        //}
        if(isThrow)
        {
            flyingTimer += Time.fixedDeltaTime; // 累计飞行时间
            if (flyingTimer >= 30f) // 超过10秒立即销毁
            {
                Destroy(gameObject);
                return;
            }
            HandleFlyingMovement();
            //CheckCollisions();
        }else if(isPlatform) 
        {
            if ((platformDuration -= Time.fixedDeltaTime) <= 0)
                   EnterFallingState();
        }
    }

    private void HandleFlyingMovement()
    {
        // 使用调整后的加速度计算新速度
        float newSpeed = rb.velocity.x + acceleration * Time.fixedDeltaTime;
        newSpeed = Mathf.Clamp(newSpeed, -maxReturnSpeed, maxReturnSpeed);
        rb.velocity = new Vector2(newSpeed, 0);
    }

    //private void CheckCollisions()
    //{
    //    Collider2D[] hits = Physics2D.OverlapBoxAll(
    //        col.bounds.center,
    //        detectionSize,
    //        0,
    //        groundLayer
    //    );

    //    foreach (var hit in hits)
    //    {            
    //        if (hit != null && hit != col)
    //        {
    //            EnterPlatformState();
    //            return;
    //        }
    //    }
    //}

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(!isCatch && isThrow && (1<<collision.gameObject.layer & groundLayer)!=0)
        {
            GameObject.Destroy(gameObject);
        }

        if(isThrow && LayerMask.LayerToName(collision.gameObject.layer).Equals("Player"))
        {
            EnterPlatformState();
        }
    }

    #endregion

    #region 状态切换

    private void EnterFlyingState()
    {
        //rb.bodyType = RigidbodyType2D.Dynamic;
        //col.isTrigger = true;
        isThrow = true;
        isCatch = false;
        rb.velocity = moveDirection * launchSpeed;
        //gameObject.layer = LayerMask.NameToLayer("Boomerang"); // 需创建该层
    }

    bool isCatch = false;
    public void EnterCatchState()
    {        
        isThrow = false; 
        isCatch = true;
        rb.velocity = Vector2.zero;
    }

    private void EnterPlatformState()
    {
        //rb.bodyType = RigidbodyType2D.Kinematic;
        isThrow = false;
        isCatch = false;
        isPlatform = true;
        rb.velocity = Vector2.zero;
        //col.isTrigger = false;
        //gameObject.layer = LayerMask.NameToLayer("Platform"); // 需创建该层
    }

    private void EnterFallingState()
    {
        StartCoroutine(FallRoutine());
        //rb.bodyType = RigidbodyType2D.Dynamic;
        rb.gravityScale = fallGravity;
        Destroy(gameObject, 2f);
    }

    private IEnumerator FallRoutine()
    {
        for (int i = 0; i < 10; i++)
        {
            spriteRenderer.enabled = !spriteRenderer.enabled;
            yield return new WaitForSeconds(flashInterval);
        }
    }

    #endregion

    #region 调试

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(transform.position, detectionSize);
    }

    #endregion
}